// Source File Name:   SmartUpload.java

package shmged.com.shlcm.utils;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Vector;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;

// Referenced classes of package com.jspsmart.upload:
//            Files, Request, SmartUploadException, File

public class CmSmartUpload {
    protected byte m_binArray[];
    protected HttpServletRequest m_request;
    protected HttpServletResponse m_response;
    protected ServletContext m_application;
    private int m_totalBytes;
    private int m_currentIndex;
    private int m_startData;
    private int m_endData;
    private String m_boundary;
    private long m_totalMaxFileSize;
    private long m_maxFileSize;
    private Vector m_deniedFilesList;
    private Vector m_allowedFilesList;
    private boolean m_denyPhysicalPath;
    private String m_contentDisposition;
    public static final int SAVE_AUTO = 0;
    public static final int SAVE_VIRTUAL = 1;
    public static final int SAVE_PHYSICAL = 2;
    private CmFiles m_files;
    private Request m_formRequest;
    private String m_charset;

    public CmSmartUpload() {
        m_totalBytes = 0;
        m_currentIndex = 0;
        m_startData = 0;
        m_endData = 0;
        m_boundary = new String();
        m_totalMaxFileSize = 0L;
        m_maxFileSize = 0L;
        m_deniedFilesList = new Vector();
        m_allowedFilesList = new Vector();
        m_denyPhysicalPath = false;
        m_contentDisposition = new String();
        m_files = new CmFiles();
        m_formRequest = new Request();
        m_charset = null;
    }

    /**
     * @deprecated Method init is deprecated
     */

    public final void init(ServletConfig servletconfig) {
        m_application = servletconfig.getServletContext();
    }

    /**
     * use charset for string convert if charset not null, otherwise use the system default charset
     *
     * @param charset
     */
    public void setCharset(String charset) {
        m_charset = charset;
    }

    /**
     * @deprecated Method service is deprecated
     */

    public void service(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse) {
        m_request = httpservletrequest;
        m_response = httpservletresponse;
    }

    public final void initialize(ServletConfig servletconfig, HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse) {
        m_application = servletconfig.getServletContext();
        m_request = httpservletrequest;
        m_response = httpservletresponse;
    }

    public final void initialize(PageContext pagecontext) {
        m_application = pagecontext.getServletContext();
        m_request = (HttpServletRequest) pagecontext.getRequest();
        m_response = (HttpServletResponse) pagecontext.getResponse();
    }

    /**
     * @deprecated Method initialize is deprecated
     */
    public final void initialize(ServletContext servletcontext, HttpSession httpsession, HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, JspWriter jspwriter) {
        m_application = servletcontext;
        m_request = httpservletrequest;
        m_response = httpservletresponse;
    }

    public void upload()
            throws ServletException, IOException, SmartUploadException {
        int i = 0;
        long totalFileSize = 0L;
        boolean isNewline = false;
        String filename ="";
        String fileExt = "";
        String filePathName ="";
        String contentType = "";
        String contentDisp = "";
        String typeMIME = "";
        String subTypeMIME = "";
        int length = 0;
        if (true) {
            InputStream is = m_request.getInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            while ((length = is.read(buf)) >= 0)
                bos.write(buf, 0, length);
            m_binArray = bos.toByteArray();
            m_totalBytes = m_binArray.length;
            // debug
            //saveToFile(m_binArray);
        }
        else {
            m_totalBytes = m_request.getContentLength();
            m_binArray = new byte[m_totalBytes];
            for (; i < m_totalBytes && length >= 0; i += length) {
                try {
                    m_request.getInputStream();
                    length = m_request.getInputStream().read(m_binArray, i, m_totalBytes - i);
                }
                catch (Exception exception) {
                    throw new SmartUploadException("Unable to upload.");
                }
            }
            // debug
            //saveToFile(m_binArray);
        }

        for (; !isNewline && m_currentIndex < m_totalBytes; m_currentIndex++)
            if (m_binArray[m_currentIndex] == 13)
                isNewline = true;
            else
                m_boundary = m_boundary + (char) m_binArray[m_currentIndex];

        if (m_currentIndex == 1)
            return;
        for (m_currentIndex++; m_currentIndex < m_totalBytes; m_currentIndex = m_currentIndex + 2) {
            String header = getDataHeader();
            m_currentIndex = m_currentIndex + 2;
            boolean hasFileData = header.indexOf("filename") > 0;
            String fieldname = getDataFieldValue(header, "name");
            if (hasFileData) {
                filePathName = getDataFieldValue(header, "filename");
                filename = getFileName(filePathName);
                fileExt = getFileExt(filename);
                contentType = getContentType(header);
                contentDisp = getContentDisp(header);
                typeMIME = getTypeMIME(contentType);
                subTypeMIME = getSubTypeMIME(contentType);
            }
            getDataSection();
            //System.out.println(fieldname + ": " + m_startData + " - " + m_endData +
            //        " of " + m_totalBytes + ", " + (hasFileData ? "file" : "data"));
            if (hasFileData && filename.length() > 0) {
                if (m_deniedFilesList.contains(fileExt))
                    throw new SecurityException("The extension of the file is denied to be uploaded (1015).");
                if (!m_allowedFilesList.isEmpty() && !m_allowedFilesList.contains(fileExt))
                    throw new SecurityException("The extension of the file is not allowed to be uploaded (1010).");
                if (m_maxFileSize > 0L && (long) ((m_endData - m_startData) + 1) > m_maxFileSize)
                    throw new SecurityException("Size exceeded for this file : " + filename + " (1105).");
                totalFileSize += (m_endData - m_startData) + 1;
                if (m_totalMaxFileSize > 0L && totalFileSize > m_totalMaxFileSize)
                    throw new SecurityException("Total File Size exceeded (1110).");
            }
            if (hasFileData) {
                CmFiles.File file = new CmFiles.File();
                file.setParent(this);
                file.setFieldName(fieldname);
                file.setFileName(filename);
                file.setFileExt(fileExt);
                file.setFilePathName(filePathName);
                file.setIsMissing(filePathName.length() == 0);
                file.setContentType(contentType);
                file.setContentDisp(contentDisp);
                file.setTypeMIME(typeMIME);
                file.setSubTypeMIME(subTypeMIME);
                if (contentType.indexOf("application/x-macbinary") > 0)
                    m_startData = m_startData + 128;
                file.setSize((m_endData - m_startData) + 1);
                file.setStartData(m_startData);
                file.setEndData(m_endData);
                m_files.addFile(file);
                //System.out.println("file: " + fieldname + "=" + filePathName);
            } else {
                String strFieldValue;                
                if (m_charset == null)
                    strFieldValue = new String(m_binArray, m_startData, (m_endData - m_startData) + 1);
                else {
                    try {
                        strFieldValue = new String(m_binArray, m_startData, (m_endData - m_startData) + 1, m_charset);
                    }
                    catch(UnsupportedEncodingException e) {
                        strFieldValue = new String(m_binArray, m_startData, (m_endData - m_startData) + 1);
                    }
                }
                //System.out.println("file: " + fieldname + "=" + strFieldValue);
                m_formRequest.putParameter(fieldname, strFieldValue);
            }
            if ((char) m_binArray[m_currentIndex + 1] == '-')
                break;
        }
    }

    public int save(String s)
            throws ServletException, IOException, SmartUploadException {
        return save(s, 0);
    }

    public int save(String s, int i)
            throws ServletException, IOException, SmartUploadException {
        int j = 0;
        if (s == null)
            s = m_application.getRealPath("/");
        if (s.indexOf("/") != -1) {
            if (s.charAt(s.length() - 1) != '/')
                s = s + "/";
        } else if (s.charAt(s.length() - 1) != '\\')
            s = s + "\\";
        for (int k = 0; k < m_files.getCount(); k++)
            if (!m_files.getFile(k).isMissing()) {
                m_files.getFile(k).saveAs(s + m_files.getFile(k).getFileName(), i);
                j++;
            }

        return j;
    }

    public int getSize() {
        return m_totalBytes;
    }

    public byte getBinaryData(int i) {
        byte byte0;
        try {
            byte0 = m_binArray[i];
        }
        catch (Exception exception) {
            throw new ArrayIndexOutOfBoundsException("Index out of range (1005).");
        }
        return byte0;
    }

    public CmFiles getFiles() {
        return m_files;
    }

    public Request getRequest() {
        return m_formRequest;
    }
    
    public String getParameter(String s) {
        return m_formRequest.getParameter(s);
    }
    
    public String[] getParameterValues(String s) {
        return m_formRequest.getParameterValues(s);
    }
    
    public Enumeration getParameterNames() {
        return m_formRequest.getParameterNames();
    }
    
    @SuppressWarnings("unchecked")
    public Map getParameterMap() {
        Map m = new HashMap();
        for (Enumeration en = getParameterNames(); en.hasMoreElements();) {
            String name = (String) en.nextElement();
            String[] vals = getParameterValues(name);
            m.put(name, vals);
        }
        return m;
    }

    public void downloadFile(String s)
            throws ServletException, IOException, SmartUploadException {
        downloadFile(s, null, null);
    }

    public void downloadFile(String s, String s1)
            throws ServletException, IOException, SmartUploadException, SmartUploadException {
        downloadFile(s, s1, null);
    }

    public void downloadFile(String s, String s1, String s2)
            throws ServletException, IOException, SmartUploadException {
        downloadFile(s, s1, s2, 65000);
    }

    public void downloadFile(String s, String s1, String s2, int i)
            throws ServletException, IOException, SmartUploadException {
        if (s == null)
            throw new IllegalArgumentException("File '" + s + "' not found (1040).");
        if (s.equals(""))
            throw new IllegalArgumentException("File '" + s + "' not found (1040).");
        if (!isVirtual(s) && m_denyPhysicalPath)
            throw new SecurityException("Physical path is denied (1035).");
        if (isVirtual(s))
            s = m_application.getRealPath(s);
        java.io.File file = new java.io.File(s);
        FileInputStream fileinputstream = new FileInputStream(file);
        long l = file.length();
        int k = 0;
        byte abyte0[] = new byte[i];
        if (s1 == null)
            m_response.setContentType("application/x-msdownload");
        else if (s1.length() == 0)
            m_response.setContentType("application/x-msdownload");
        else
            m_response.setContentType(s1);
        m_response.setContentLength((int) l);
        m_contentDisposition = m_contentDisposition != null ? m_contentDisposition : "attachment;";
        if (s2 == null)
            m_response.setHeader("Content-Disposition", m_contentDisposition + " filename=" + getFileName(s));
        else if (s2.length() == 0)
            m_response.setHeader("Content-Disposition", m_contentDisposition);
        else
            m_response.setHeader("Content-Disposition", m_contentDisposition + " filename=" + s2);
        while ((long) k < l) {
            int j = fileinputstream.read(abyte0, 0, i);
            k += j;
            m_response.getOutputStream().write(abyte0, 0, j);
        }
        fileinputstream.close();
    }

    public void downloadField(ResultSet resultset, String s, String s1, String s2)
            throws ServletException, IOException, SQLException {
        if (resultset == null)
            throw new IllegalArgumentException("The RecordSet cannot be null (1045).");
        if (s == null)
            throw new IllegalArgumentException("The columnName cannot be null (1050).");
        if (s.length() == 0)
            throw new IllegalArgumentException("The columnName cannot be empty (1055).");
        byte abyte0[] = resultset.getBytes(s);
        if (s1 == null)
            m_response.setContentType("application/x-msdownload");
        else if (s1.length() == 0)
            m_response.setContentType("application/x-msdownload");
        else
            m_response.setContentType(s1);
        m_response.setContentLength(abyte0.length);
        if (s2 == null)
            m_response.setHeader("Content-Disposition", "attachment;");
        else if (s2.length() == 0)
            m_response.setHeader("Content-Disposition", "attachment;");
        else
            m_response.setHeader("Content-Disposition", "attachment; filename=" + s2);
        m_response.getOutputStream().write(abyte0, 0, abyte0.length);
    }

    public void fieldToFile(ResultSet resultset, String s, String s1)
            throws ServletException, IOException, SmartUploadException, SQLException {
        try {
            if (m_application.getRealPath(s1) != null)
                s1 = m_application.getRealPath(s1);
            InputStream inputstream = resultset.getBinaryStream(s);
            FileOutputStream fileoutputstream = new FileOutputStream(s1);
            int i;
            while ((i = inputstream.read()) != -1)
                fileoutputstream.write(i);
            fileoutputstream.close();
        }
        catch (Exception exception) {
            throw new SmartUploadException("Unable to save file from the DataBase (1020).");
        }
    }

    private String getDataFieldValue(String field, String fieldname) {
        String value = "";
        String tempStr = fieldname + "=" + '"';
        int pos = field.indexOf(tempStr);
        if (pos > 0) {
            int fromPos = pos + tempStr.length();
            int toPos = field.indexOf("\"", fromPos);
            if (fromPos > 0 && toPos > 0)
                value = field.substring(fromPos, toPos);
        }
        return value;
    }

    private String getFileExt(String s) {
        String s1 = new String();
        int i = 0;
        int j = 0;
        if (s == null)
            return null;
        i = s.lastIndexOf('.') + 1;
        j = s.length();
        s1 = s.substring(i, j);
        if (s.lastIndexOf('.') > 0)
            return s1;
        else
            return "";
    }

    private String getContentType(String s) {
        String s1 = new String();
        String s2 = new String();
        int i = 0;
        //boolean flag = false;
        s1 = "Content-Type:";
        i = s.indexOf(s1) + s1.length();
        if (i != -1) {
            int j = s.length();
            s2 = s.substring(i, j);
        }
        return s2;
    }

    private String getTypeMIME(String s) {
        //String s1 = new String();
        int i = 0;
        i = s.indexOf("/");
        if (i != -1)
            return s.substring(1, i);
        else
            return s;
    }

    private String getSubTypeMIME(String s) {
        //String s1 = new String();
        int i = 0;
        //boolean flag = false;
        i = s.indexOf("/") + 1;
        if (i != -1) {
            int j = s.length();
            return s.substring(i, j);
        } else {
            return s;
        }
    }

    private String getContentDisp(String s) {
        String s1 = new String();
        int i = 0;
        int j = 0;
        i = s.indexOf(":") + 1;
        j = s.indexOf(";");
        s1 = s.substring(i, j);
        return s1;
    }

    private void getDataSection() {
        //String s = new String();
        int i = m_currentIndex;
        int j = 0;
        int k = m_boundary.length();
        m_startData = m_currentIndex;
        m_endData = 0;
        while (i < m_totalBytes)
            if (m_binArray[i] == (byte) m_boundary.charAt(j)) {
                if (j == k - 1) {
                    m_endData = ((i - k) + 1) - 3;
                    break;
                }
                i++;
                j++;
            } else {
                i++;
                j = 0;
            }
        if (m_endData == 0) {
            System.out.println("boundary not found: " + m_startData + " - " + (m_totalBytes - 1));
            m_endData = m_totalBytes - 1;
        }
        m_currentIndex = m_endData + k + 3;
    }

    private String getDataHeader() {
        String header;

        int startIndex = m_currentIndex;
        int endIndex = 0;
        for (boolean flag = false; !flag;)
            if (m_binArray[m_currentIndex] == 13 && m_binArray[m_currentIndex + 2] == 13) {
                flag = true;
                endIndex = m_currentIndex - 1;
                m_currentIndex = m_currentIndex + 2;
            } else {
                m_currentIndex++;
            }
        if (m_charset != null) {
            try {
                header = new String(m_binArray, startIndex, (endIndex - startIndex) + 1, m_charset);
            } catch (UnsupportedEncodingException e) {
                header = new String(m_binArray, startIndex, (endIndex - startIndex) + 1);
            }
        }
        else
            header = new String(m_binArray, startIndex, (endIndex - startIndex) + 1);
        return  header;
    }

    private String getFileName(String s) {
        int i = s.lastIndexOf('/');
        if (i != -1)
            return s.substring(i + 1, s.length());
        i = s.lastIndexOf('\\');
        if (i != -1)
            return s.substring(i + 1, s.length());
        else
            return s;
    }

    @SuppressWarnings("unchecked")
    public void setDeniedFilesList(String s)
            throws ServletException, IOException, SQLException {
        //String s1 = "";
        if (s != null) {
            String s2 = "";
            for (int i = 0; i < s.length(); i++)
                if (s.charAt(i) == ',') {
                    if (!m_deniedFilesList.contains(s2))
                        m_deniedFilesList.addElement(s2);
                    s2 = "";
                } else {
                    s2 = s2 + s.charAt(i);
                }

            if (s2 != "")
                m_deniedFilesList.addElement(s2);
        } else {
            m_deniedFilesList = null;
        }
    }

    @SuppressWarnings("unchecked")
    public void setAllowedFilesList(String s) {
        //String s1 = "";
        if (s != null) {
            String s2 = "";
            for (int i = 0; i < s.length(); i++)
                if (s.charAt(i) == ',') {
                    if (!m_allowedFilesList.contains(s2))
                        m_allowedFilesList.addElement(s2);
                    s2 = "";
                } else {
                    s2 = s2 + s.charAt(i);
                }

            if (s2 != "")
                m_allowedFilesList.addElement(s2);
        } else {
            m_allowedFilesList = null;
        }
    }

    public void setDenyPhysicalPath(boolean flag) {
        m_denyPhysicalPath = flag;
    }

    public void setContentDisposition(String s) {
        m_contentDisposition = s;
    }

    public void setTotalMaxFileSize(long l) {
        m_totalMaxFileSize = l;
    }

    public void setMaxFileSize(long l) {
        m_maxFileSize = l;
    }

    protected String getPhysicalPath(String s, int i)
            throws IOException {
        String s1 = new String();
        String s2 = new String();
        String s3 = new String();
        boolean flag = false;
        s3 = System.getProperty("file.separator");
        if (s == null)
            throw new IllegalArgumentException("There is no specified destination file (1140).");
        if (s.equals(""))
            throw new IllegalArgumentException("There is no specified destination file (1140).");
        if (s.lastIndexOf("\\") >= 0) {
            s1 = s.substring(0, s.lastIndexOf("\\"));
            s2 = s.substring(s.lastIndexOf("\\") + 1);
        }
        if (s.lastIndexOf("/") >= 0) {
            s1 = s.substring(0, s.lastIndexOf("/"));
            s2 = s.substring(s.lastIndexOf("/") + 1);
        }
        s1 = s1.length() != 0 ? s1 : "/";
        java.io.File file = new java.io.File(s1);
        if (file.exists())
            flag = true;
        if (i == 0) {
            if (isVirtual(s1)) {
                s1 = m_application.getRealPath(s1);
                if (s1.endsWith(s3))
                    s1 = s1 + s2;
                else
                    s1 = s1 + s3 + s2;
                return s1;
            }
            if (flag) {
                if (m_denyPhysicalPath)
                    throw new IllegalArgumentException("Physical path is denied (1125).");
                else
                    return s;
            } else {
                throw new IllegalArgumentException("This path does not exist (1135).");
            }
        }
        if (i == 1) {
            if (isVirtual(s1)) {
                s1 = m_application.getRealPath(s1);
                if (s1.endsWith(s3))
                    s1 = s1 + s2;
                else
                    s1 = s1 + s3 + s2;
                return s1;
            }
            if (flag)
                throw new IllegalArgumentException("The path is not a virtual path.");
            else
                throw new IllegalArgumentException("This path does not exist (1135).");
        }
        if (i == 2) {
            if (flag)
                if (m_denyPhysicalPath)
                    throw new IllegalArgumentException("Physical path is denied (1125).");
                else
                    return s;
            if (isVirtual(s1))
                throw new IllegalArgumentException("The path is not a physical path.");
            else
                throw new IllegalArgumentException("This path does not exist (1135).");
        } else {
            return null;
        }
    }

    public void uploadInFile(String s)
            throws IOException, SmartUploadException {
        int i = 0;
        int j = 0;
        //boolean flag = false;
        if (s == null)
            throw new IllegalArgumentException("There is no specified destination file (1025).");
        if (s.length() == 0)
            throw new IllegalArgumentException("There is no specified destination file (1025).");
        if (!isVirtual(s) && m_denyPhysicalPath)
            throw new SecurityException("Physical path is denied (1035).");
        i = m_request.getContentLength();
        m_binArray = new byte[i];
        int k;
        for (; j < i; j += k)
            try {
                k = m_request.getInputStream().read(m_binArray, j, i - j);
            }
            catch (Exception exception) {
                throw new SmartUploadException("Unable to upload.");
            }

        if (isVirtual(s))
            s = m_application.getRealPath(s);
        try {
            java.io.File file = new java.io.File(s);
            FileOutputStream fileoutputstream = new FileOutputStream(file);
            fileoutputstream.write(m_binArray);
            fileoutputstream.close();
        }
        catch (Exception exception1) {
            throw new SmartUploadException("The Form cannot be saved in the specified file (1030).");
        }
    }

    private boolean isVirtual(String s) {
        if (m_application.getRealPath(s) != null) {
            java.io.File file = new java.io.File(m_application.getRealPath(s));
            return file.exists();
        } else {
            return false;
        }
    }

    static void saveToFile(byte[] bytes) throws IOException {
        java.io.File file = java.io.File.createTempFile("smart", ".tmp");
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(bytes);
        fos.close();
        System.out.println("save post stream: " + file.getCanonicalPath());
    }
}

class SmartUploadException extends Exception
{
    private static final long serialVersionUID = 1L;

    SmartUploadException(String s)
    {
        super(s);
    }
}

class Request {
    private Hashtable m_parameters;

    Request() {
        m_parameters = new Hashtable();
    }

    @SuppressWarnings("unchecked")
    protected void putParameter(String s, String s1) {
        if (s == null)
            throw new IllegalArgumentException("The name of an element cannot be null.");
        if (m_parameters.containsKey(s)) {
            Hashtable hashtable = (Hashtable) m_parameters.get(s);
            hashtable.put(new Integer(hashtable.size()), s1);
        } else {
            Hashtable hashtable1 = new Hashtable();
            hashtable1.put(new Integer(0), s1);
            m_parameters.put(s, hashtable1);
        }
    }

    public String getParameter(String s) {
        if (s == null)
            throw new IllegalArgumentException("Form's name is invalid or does not exist (1305).");
        Hashtable hashtable = (Hashtable) m_parameters.get(s);
        if (hashtable == null)
            return null;
        else
            return (String) hashtable.get(new Integer(0));
    }

    public Enumeration getParameterNames() {
        return m_parameters.keys();
    }

    public String[] getParameterValues(String s) {
        if (s == null)
            throw new IllegalArgumentException("Form's name is invalid or does not exist (1305).");
        Hashtable hashtable = (Hashtable) m_parameters.get(s);
        if (hashtable == null)
            return null;
        String as[] = new String[hashtable.size()];
        for (int i = 0; i < hashtable.size(); i++)
            as[i] = (String) hashtable.get(new Integer(i));

        return as;
    }
}